<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <template #before>
          <span>共{{ total }}条数据</span>
        </template>
        <template #after>
          <el-button type="success" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="exportData">excel导出</el-button>
          <el-button icon="el-icon-plus" size="small" type="primary" @click="addEmployee">新增员工</el-button>
        </template>
      </PageTools>
      <el-card>
        <el-table
          v-loading="loading"
          :data="list"
          border
          style="width: 100%"
        >
          <el-table-column
            type="index"
            label="序号"
            width="150"
          />
          <el-table-column
            prop="username"
            label="姓名"
            width="150"
            sortable
          />
          <el-table-column label="头像" header-align="left" align="center" width="150px">
            <template v-slot="{row}">
              <img v-imagerror="require('@/assets/common/head.jpg')" :src="row.staffPhoto" style="border-radius:50%; width:100px; height:100px;padding:10px" @click="showQrCode(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column
            prop="mobile"
            label="手机号"
            width="150"
            sortable
          /><el-table-column
            prop="workNumber"
            label="工号"
            width="150"
            sortable
          />
          <el-table-column
            prop="formOfEmployment"
            :formatter="formatEmoloyeement"
            label="聘用形式"
            width="150"
            sortable
          />
          <el-table-column
            prop="departmentName"
            label="部门"
            width="150"
            sortable
          />
          <el-table-column
            prop="timeOfEntry"
            label="入职时间"
            width="150"
            sortable
          >
            <template v-slot="obj">
              {{ obj.row.timeOfEntry | formatDate }}
            </template>
            <!-- 时间过滤器 -->
          </el-table-column>
          <el-table-column
            prop="enableState"
            label="账户状态"
            width="150"
            sortable
          >
            <template v-slot="{row}">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="400"
            align="center"
          >
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="deleteEmployeer(row.id)">删除</el-button>
            </template>

          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height:60px;">
          <el-pagination :page-size="page.size" :total="total" :current-page="page.page" layout="slot,prev,pager,next" @current-change="currentChange">
            <span>共{{ total }}条</span>
          </el-pagination>
        </el-row>
      </el-card>
    </div>
    <!-- 新增员工弹层 -->
    <addEmployee :show-dialog="showDialog" @closeCanel="showDialog = false" />

    <!-- 二维码弹层 -->
    <el-dialog title="二维码" :visible.sync="showCodeDialog">
      <!-- 显示二维码弹层 -->
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 分配角色弹层 -->
    <component :is="Role" ref="getUserDatailById" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { formatDate } from '@/filters'
import { getEmployeeList } from '@/api/employees'
import { deleteEmployee } from '@/api/employees'
import addEmployee from './compnents/add-employee.vue'
import EmployeeEnum from '@/api/constant/employees'// 引入员工枚举对象
import QrCode from 'qrcode'
import Role from './assign/role.vue'
export default {
  components: {
    addEmployee,
    Role
  },
  data() {
    return {
      page: {
        page: 1,
        size: 10
      },
      total: 0,
      list: [],
      loading: false,
      showDialog: false,
      showCodeDialog: false,
      Role: 'Role',
      showRoleDialog: false,
      userId: null // 定义用户ID
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.list = rows
      this.total = total
      this.loading = false
      // console.log(rows)
    },
    currentChange(newpage) {
      this.page.page = newpage
      this.getEmployeeList()
      console.log(this.page.page)
    },
    // 格式化聘用格式
    formatEmoloyeement(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)

      return obj ? obj.value : '未知'
    },
    // 删除员工
    deleteEmployeer(id) {
      this.$confirm('您确定删除此员工吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteEmployee(id)
        this.getEmployeeList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
    },
    // 新增员工
    addEmployee() {
      this.showDialog = true
    },
    // addEmployees() {
    //   this.$refs.addEmployees.addEmployee()
    //   this.getEmployeeList()
    //   this.$message.success('添加员工成功')
    // }
    exportData() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      // 导出excel

      // excel懒加载
      import('@/vendor/Export2Excel').then(async excel => {
      // 引入文件导出的对象
      // 导出：1表头  2.数据从哪里来

        const { rows } = await getEmployeeList({
          page: 1,
          size: this.total
        })
        // console.log(headers)
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        const data = this.formatJson(rows, headers)
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工资料表',
          multiHeader, // 复杂表头
          merges // 合并选项
        })
        // excel.export_json_to_excel({
        //   header: ['姓名', '工资'],
        //   data: [],
        //   filename: '员工工资表'

        // })
      })
    },
    // 将表头数据和数据进行对应
    // [[]]  [{}]
    formatJson(rows, headers) {
      return rows.map(item => {
        // item是一个对象 {mobile:123,username:'张三'}
        // 根据表头数据转
        // ['手机号'，'姓名','入职日期']
        return Object.keys(headers).map(key => {
          // 判断时间
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            // 格式化日期
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
            // console.log(obj)

            return obj ? obj.value : '未知'
          }
          return item[headers[key]]
          //  ['132','站桑','','']
        })
      })
    },
    async showQrCode(url) {
      // url存在情况下才弹出层
      if (url) {
        this.showCodeDialog = true
        //  页面渲染是异步的，弹层没有出现，不能直接获取$ref
        await this.$nextTick()
        QrCode.toCanvas(this.$refs.myCanvas, url)// 将地址转化成二维码信息
        // 第二个如果是url地址,就会跳转到url地址上
      } else {
        this.$message.warning('该用户暂未上传头像')
      }
    },
    async editRole(id) {
      this.userId = id
      await this.$refs.getUserDatailById.getUserDatailById(id)
      this.showRoleDialog = true
      // await this.$nextTick()
    }
  }
}

</script>

<style>

</style>
